package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    Configuration configuration;
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    ApArticleMapper apArticleMapper;


    //处理文章详情页   静态化后得到源代码  存储到minio 同时更新ap_article表的static_url字段     异步执行
    @Override
    @Async//标注当前方法是异步方法
    public void buildArticleContentToMinio(ApArticle article, String content) {
        log.info("FreemarkerServiceImpl  buildArticleContentToMinio 处理详情数据   线程名称:{}", Thread.currentThread().getName());
        //1.校验
        if(StringUtils.isBlank(content) || article==null || article.getId()==null){
            return;
        }

        //2.freemarker 静态化
        StringWriter stringWriter =  new StringWriter();
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));
            template.process(map, stringWriter);
            System.out.println(stringWriter.toString());
        } catch (Exception e) {
            log.error("获取模版失败 ",e);
            return;
        }

        //3.存minio
        ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
        String htmlFile = fileStorageService.uploadHtmlFile(null, article.getId() + ".html", inputStream);
        System.out.println("htmlFile:" +htmlFile);

        //4.更新ap_article 表static_url
        article.setStaticUrl(htmlFile);
        apArticleMapper.updateById(article);



        //发送消息到kafka  将文章索引到es
        sendArticleToKafka(article, content);

    }

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
    /**
     *  发送文章消息到kafka
     * @param article
     * @param content
     */
    private void sendArticleToKafka(ApArticle article, String content) {
        SearchArticleVo vo  = new SearchArticleVo();
        BeanUtils.copyProperties(article, vo);
        vo.setContent(content);
        String jsonString = JSON.toJSONString(vo);

        log.info("发送消息到kafka 索引文章到es  {}", jsonString);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, jsonString);
    }
}
